package com.seckill.config;

import com.seckill.access.UserContext;
import com.seckill.domain.MiaoshaUser;
import com.seckill.service.MiaoshaUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 自定义参数处理类
 * 请求进来，先过拦截器，然后再经过参数处理器
 *
 * @author yangjunwei
 * @date 2021/11/1 9:34 上午
 */
@Service
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    MiaoshaUserService miaoshaUserService;

    /**
     * 满足条件，进行 resolveArgument 里的逻辑处理
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        Class<?> parameterType = methodParameter.getParameterType();
        //请求参数包含MiaoshaUser时满足
        return parameterType == MiaoshaUser.class;
    }

    @Override
    public MiaoshaUser resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory webDataBinderFactory) {
        //统一拦截时的用户信息
        MiaoshaUser miaoshaUser = UserContext.getMiaoshaUser();
        UserContext.removeUser();
        return miaoshaUser;
    }

//    @Override
//    public MiaoshaUser resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
//                                       NativeWebRequest webRequest, WebDataBinderFactory webDataBinderFactory) {
//        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
//        HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
//        //获取token
//        String paramToken = request.getParameter(MiaoshaUserService.COOKIE_NAME);
//        String cookieValue = getCookieValue(request, MiaoshaUserService.COOKIE_NAME);
//        if (StringUtils.isEmpty(cookieValue) && StringUtils.isEmpty(paramToken)) {
//            return null;
//        }
//        //若cookie中不存在token，使用param的token
//        String token = StringUtils.isEmpty(cookieValue) ? paramToken : cookieValue;
//        //从缓存获取用户信息
//        return miaoshaUserService.getMiaoshaUserByToken(response, token);
//    }


}
